﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Plateformer : Character {

	public float jumpForce = GameSystem.jumpForce;
	public float plateformerMovingSpeed = GameSystem.plateformerMovingSpeed;
	public float acceleration = 1.0f;
	public float deceleration = 1.0f;
	public float gravity = 1.0f;
	public float verticalKnockback = 0.5f;
	public float ascendMultiplier = 1.0f;
	public float descendMultiplier = 1.0f;
	public float maximumRunSpeed = 50.0f;
	public Transform deathAnimation;
	private Vector3 velocity, previousVelocity;
	private Vector3 previousPosition;
	private Vector3 positionBeforeDie;

	private int contactCountThisFrame = 0;
	private float timerWithoutContacts = 0.1f;
	
	private float startAttack =0;

	private bool isFlipped = false;

	private const int IDLE = 0;
	private const int JUMP = 1;
	private const int FALLING = 2;
	private const int RUN = 3;
	private const int ATTACK = 4;
	private const int DEAD = 5;


	protected override void Start ()
	{
		animator = this.GetComponent<Animator>();
	}

	protected override void Update () {
	}

	
	void FixedUpdate()
	{
		Move ();
		Display ();
	}
	protected override void OnCollisionEnter2D(Collision2D collision)
	{}

	public void Crush(bool isVertical)	
	{
		
		positionBeforeDie = transform.position;
		float baseForce = 1000;
		Transform da = Instantiate(deathAnimation, transform.position, Quaternion.AngleAxis(Random.Range(0, 360), new Vector3(0, 0, 1))) as Transform;
		if(isVertical)
		{
			int sign = -1;
			if(Random.value > 0.5f)
				sign = 1;
			da.rigidbody2D.AddForce(new Vector2(baseForce * sign, Random.Range(baseForce, baseForce * 2)));
		}
		else
		{
			int sign = -1;
			if(Random.value > 0.5f)
				sign = 1;
			da.rigidbody2D.AddForce(new Vector2(Random.Range(baseForce, baseForce * 2) * sign, baseForce));
		}
		da.rigidbody2D.AddTorque(Random.Range(50, 150));

		
		transform.position = GameSystem.startPoint.transform.position;
		GameSystem.Repop ();
		LooseCollectible ();
	}
	
	


	protected override void OnCollisionExit2D(Collision2D collision)
	{
	}

	protected override void Move()
	{
		previousVelocity = (transform.position - previousPosition) / Time.fixedDeltaTime;

		if(velocity.y > 0)
			velocity.y -= (gravity / ascendMultiplier)  * Time.fixedDeltaTime;
		else
			velocity.y -= gravity * descendMultiplier * Time.fixedDeltaTime;
		velocity.y -= gravity * Time.fixedDeltaTime;

		Vector3 verticalMove = velocity;
		verticalMove.x = 0;
		float distance =  verticalMove.magnitude * Time.fixedDeltaTime;
		verticalMove.Normalize();
		RaycastHit hit;
		if(rigidbody.SweepTest(verticalMove, out hit, distance))
		{
			float fallvelocity = velocity.y;
			if(verticalMove.y > 0)
				fallvelocity *= -1 * verticalKnockback;
			else
				fallvelocity = 0;

			velocity = new Vector3(velocity.x, fallvelocity, 0);
			base.state = Character.State.normal;
			animator.SetInteger ("Direction", IDLE);
		}

		//Jump
		if (Input.GetKey (KeyCode.UpArrow) && base.state == Character.State.normal && previousVelocity.y >= 0) {
			velocity.y += jumpForce + previousVelocity.y;
			base.state = Character.State.jumping;
			animator.SetInteger ("Direction", JUMP);
		}

		if (base.state == Character.State.jumping && rigidbody.velocity.y < 0) {
			animator.SetInteger ("Direction", FALLING);
		}

		// L/R deplacement
		if (Input.GetKey (KeyCode.LeftArrow)) {
			velocity.x = Mathf.Max(velocity.x + acceleration * Time.fixedDeltaTime * -1.0f, -maximumRunSpeed);
			if(base.state == Character.State.normal) {
				animator.SetInteger ("Direction", RUN);
			}

		} else if (Input.GetKey (KeyCode.RightArrow)) {
			velocity.x = Mathf.Min(velocity.x + acceleration * Time.fixedDeltaTime, maximumRunSpeed);
			if(base.state == Character.State.normal) {
				animator.SetInteger ("Direction", RUN);
			}
		} else {
			if(base.state == Character.State.normal) {
				animator.SetInteger ("Direction", IDLE);
			}
			if(state == State.movingLeft)	
				velocity.x = Mathf.Min(velocity.x + deceleration * Time.fixedDeltaTime, 0);
			else
				velocity.x = Mathf.Max(velocity.x - deceleration * Time.fixedDeltaTime, 0);
		} 

		//Hit
		if (Input.GetKey (KeyCode.Space))	
		{
			startAttack = Time.time;
			if(!transform.FindChild("AttackTrigger").collider.enabled) {
				transform.FindChild("AttackTrigger").collider.enabled = true;
				GameObject.Find("SoundManager").GetComponent<SoundPlayer>().LaunchCoroutSound((int)(Random.Range(15, 18)), 0f);
			}
			animator.SetInteger ("Direction", ATTACK);
		}

		if (startAttack!=0 && Time.time - startAttack > 0.1f)
		{
			startAttack =0;
			transform.FindChild("AttackTrigger").collider.enabled = false;
			Debug.Log("unattack");
			animator.SetInteger ("Direction", IDLE);
		}

		Vector3 horizontalMove = velocity;
		horizontalMove.y = 0;
		distance =  horizontalMove.magnitude * Time.fixedDeltaTime;
		horizontalMove.Normalize();
		if(rigidbody.SweepTest(horizontalMove, out hit, distance))
		{
			velocity = new Vector3(0, velocity.y, 0);
		}


		rigidbody.velocity = velocity;
		previousPosition = transform.position;

		if (rigidbody.velocity.x > 0) {
			isFlipped = false;
		} else if (rigidbody.velocity.x < 0) {
			isFlipped = true;
		}

		if(transform.localScale.x > 0 && isFlipped || transform.localScale.x < 0 && !isFlipped) {
			Vector3 scale = transform.localScale;
			scale.x *= -1;
			transform.localScale = scale;
		}
	}
	
	protected override void Display()
	{
	}

	protected void LooseCollectible()
	{
		

		if (GameSystem.plateformer.transform.FindChild ("SpinningAnchor").GetComponent<SpinningAnchor> ().m_anchorChildren.Count > 0) {
			GameSystem.mastermind.transform.FindChild ("SpinningAnchor").GetComponent<SpinningAnchor> ().Add ();
			Transform trans = GameSystem.plateformer.transform.FindChild ("SpinningAnchor").GetComponent<SpinningAnchor> ().m_anchorChildren [0];
			GameSystem.plateformer.transform.FindChild ("SpinningAnchor").GetComponent<SpinningAnchor> ().m_anchorChildren.Remove (trans);
			Destroy(trans.gameObject);
		}


	}
}
